package com.example.jdbc.controller;

import com.example.jdbc.pojo.User;
import com.example.jdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/addUser")
    public ModelAndView addUserMethod(User user) {

        try {
            this.userService.addUser(user);
        } catch (Exception e) {
            return new ModelAndView("redirect:/error");
        }
        /**
         * 重定向之后，客户端会重新请求success资源，经过@RequestMapping("/{path}")跳转到
         * resources/templates中，访问模版资源
         */
        return new ModelAndView("redirect:/success");
    }

    @GetMapping("/getAllUsers")
    public ModelAndView getAllUsers() {
        ModelAndView modelAndView = new ModelAndView("userList");
        List<User> userList = this.userService.getAllUsers();
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }

    @GetMapping("/preModifyUser/{userId}")
    public ModelAndView preModifyUser(@PathVariable int userId) {
        ModelAndView modelAndView = new ModelAndView("/preModifyUser");
        User user = this.userService.getUserById(userId);
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @PostMapping("/updateUser")
    public ModelAndView updateUser(User user) {
        ModelAndView modelAndView = new ModelAndView();
        System.out.println("user = " + user);
        try {
            this.userService.updateUserByUserId(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("redirect:/error");
        }
        modelAndView.setViewName("redirect:/success");
        return modelAndView;
    }

    @GetMapping("/deleteUser/{userId}")
    public ModelAndView deleteUser(@PathVariable int userId){
        ModelAndView modelAndView = new ModelAndView();
        try {
            this.userService.deleteUser(userId);
        }catch (Exception e){
            /**
             * 有几个有外键，删不了
             */
            e.printStackTrace();
            return new ModelAndView("redirect:/error");
        }
        modelAndView.setViewName("redirect:/success");
        return modelAndView;
    }
}
